<template>
	<view style="padding: 15px; box-sizing: border-box;">
		<uni-section title="项目明细" type="line">
			<div style="padding: 10px;">
				<view class="item-detail" v-for="(item, index) in detailList" :key="index">
					<p>开单时间：{{item.BillTime}}</p>
					<p>开单科室：{{item.Department}}</p>
					<p>开单医生：{{item.Doctor}}</p>
					<p>项目名称：{{item.ItemName}}</p>
					<p>项目费用：￥{{item.ItemMoney}}</p>
					<p>开具类型：{{item.ItemType}}</p>
					<p>就诊人：{{item.Name}}</p>
				</view>

				<p class="total-price">总费用：￥{{item.Money}}</p>
			</div>
		</uni-section>
		<div style="margin-bottom: 10px;"></div>
		<u-button type="success" text="缴费" @click="affirmModalVisible = true"></u-button>

		<u-modal :show="affirmModalVisible" @confirm="pay" @cancel="affirmModalVisible = false" :title="'确认'"
			:asyncClose="true" :showCancelButton="true">
			<view class="slot-content">
				<rich-text :nodes="'确认缴费吗？'"></rich-text>
			</view>
		</u-modal>

		<yangr-msg v-if="yangrMsgShow" :title="yangrMsgTitle" type="error" :info="yangrMsgMessage" btn="确定"
			@yangrMsgEvent="closeYangrMsg"></yangr-msg>
	</view>
</template>

<script>
	import yangrMsg from "@/components/yangr-msg/yangr-msg.vue"
	import onlinePay from './onlinePay.js'
	import customLogApi from "../../common/customLogApi.js"
	export default {
		components: {
			yangrMsg
		},
		data() {
			return {
				item: {},
				detailList: [],
				openid: '',
				currentUserCard: {
					names: ''
				},
				ordersn: '',
				affirmModalVisible: false,

				yangrMsgTitle: '操作失败',
				yangrMsgMessage: '',
				yangrMsgShow: false
			}
		},
		onLoad(option) {
			this.openid = uni.getStorageSync('openid')
			this.currentUserCard = uni.getStorageSync('current_user_card')
			this.item = JSON.parse(option.item)
			console.log(this.item)
			this.api_unpaiddetail(this.item.BillId)
		},
		methods: {
			closeYangrMsg() {
				this.yangrMsgShow = false
			},
			api_unpaiddetail(billid) {
				this.detailList = []
				this.$app._post_form2("entry/wxapp/apipayment.unpaiddetail", {
					"cardid": this.currentUserCard.numcard,
					"openid": this.openid,
					"billid": billid
				}, (res) => {
					console.log(res)
					this.detailList = res.data
				})
			},
			pay() {
				let flowFlag = 0
				let that = this
				onlinePay.api_addbillorder(this.openid, this.currentUserCard.numcard, this.item.BillId, this.item.Money)
					.then((res) => {
						let guahaoid = res.id
						onlinePay.setPayFlow(this.item, this.item.BillId, 1, this.item.Money, guahaoid)
						console.log(res)
						this.ordersn = res.ordersn
						onlinePay.api_icbcpay(this.openid, res.ordersn, this.item.Money).then((res) => {
							onlinePay.setPayFlow(this.item, this.item.BillId, 2, this.item.Money, guahaoid)
							console.log(res)
							let order_id = res.order_id
							let wx_data_package = JSON.parse(res.wx_data_package)
							let orderInfo = {
								"appid": wx_data_package.appid, // 应用ID（AppID）
								"package": wx_data_package.package, // 固定值
								"noncestr": wx_data_package.noncestr, // 随机字符串
								"timestamp": wx_data_package.timestamp, // 时间戳（单位：秒）
								"sign": wx_data_package.sign, // 签名，这里用的 MD5 签名
								"signtype": wx_data_package.signType
							}
							uni.requestPayment({
								"provider": "wxpay", //固定值为"wxpay"
								"timeStamp": orderInfo.timestamp,
								"nonceStr": orderInfo.noncestr,
								"package": orderInfo.package,
								"signType": orderInfo.signtype,
								"paySign": orderInfo.sign,
								success: (res) => {
									console.log(res)
									onlinePay.setPayFlow(this.item, this.item.BillId, 3, this.item.Money, guahaoid)
									console.log("支付成功");
									customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "在线缴费流程：paysucc接口开始调用")
									onlinePay.api_paysucc(this.openid, guahaoid, order_id).then((res) => {
										customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "在线缴费流程：paysucc接口调用成功，返回数据：" + JSON.stringify(res))
										onlinePay.setPayFlow(this.item, this.item.BillId, 4, this.item.Money, guahaoid)
										console.log(res)
										console.log('ordersn=' + that.ordersn)
										customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "在线缴费流程：paybill接口开始调用")
										onlinePay.api_paybill(guahaoid, this.openid, order_id, {
													"CardId": that.currentUserCard.numcard,
													"BillId": that.item.BillId,
													"Money": that.item.Money,
													"HisPaymentMethodEnum": "14",
													"PayTime": res.paytime,
													"OutTradeNo": that.ordersn
												}).then((res) => {
													console.log(res)
													customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "在线缴费流程：paybill接口调用成功，返回数据：" + JSON.stringify(res))
													if (res.status == 1 && res.data != 'none') {
														onlinePay.setPayFlow(this.item, this.item.BillId, 5, this.item.Money, guahaoid)
														const params = {
															env: 'prod',
															hospitalId: '37868',
															redirectUrl: '/pagesB/pay/index',
															sceneType: '2',
															healthCardId: that.currentUserCard.ecard_no,
															orderTotal: that.item.Money
														}
														uni.navigateTo({
															url: `plugin://healthCardPlugins/complete?env=${params.env}&hospitalId=${params.hospitalId}&sceneType=${params.sceneType}&redirect_url=${encodeURIComponent(params.redirectUrl)}&orderTotal=${params.orderTotal}&healthCardId=${params.healthCardId}`
														})
														// uni.redirectTo({
														// 	url: '/pages/global/successMessage?msg=缴费成功'
														// })
													} else {
														// uni.showToast({
														// 	title: '缴费失败',
														// 	icon: "none"
														// });
														this.yangrMsgShow = true
														this.yangrMsgMessage = '缴费失败'
													}
												})
									})
								},
								fail: (err) => {
									console.log('支付失败:' + JSON.stringify(err));
									if (err.errMsg ==
										'requestPayment:fail cancel') {
										that.affirmModalVisible = false
										uni.showToast({
											icon: 'none',
											title: '您已取消支付'
										})
									} else {
										uni.showToast({
											icon: 'none',
											title: '支付异常'
										})
									}
								}
							});
							// onlinePay.pay(orderInfo).then((res) => {
							// 	console.log(res)
							// 	// if (res.errMsg == 'requestPayment:ok') {
							// 		onlinePay.setPayFlow(this.item, this.item.BillId, 3, this.item.Money, guahaoid)
							// 		console.log("支付成功");
							// 		customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "在线缴费流程：paysucc接口开始调用")
							// 		onlinePay.api_paysucc(this.openid, guahaoid, order_id).then((res) => {
							// 			customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "在线缴费流程：paysucc接口调用成功，返回数据：" + JSON.stringify(res))
							// 			onlinePay.setPayFlow(this.item, this.item.BillId, 4, this.item.Money, guahaoid)
							// 			console.log(res)
							// 			console.log('ordersn=' + that.ordersn)
							// 			customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "在线缴费流程：paybill接口开始调用")
							// 			onlinePay.api_paybill(this.openid, order_id, {
							// 						"CardId": that.currentUserCard.numcard,
							// 						"BillId": that.item.BillId,
							// 						"Money": that.item.Money,
							// 						"HisPaymentMethodEnum": "14",
							// 						"PayTime": res.paytime,
							// 						"OutTradeNo": that.ordersn
							// 					}).then((res) => {
							// 						console.log(res)
							// 						customLogApi.saveLog(uni.getStorageSync('openid'), uni.getStorageSync('current_user_card').numcard, uni.getStorageSync('current_user_card').name, "在线缴费流程：paybill接口调用成功，返回数据：" + JSON.stringify(res))
							// 						if (res.status == 1 && res.data != 'none') {
							// 							onlinePay.setPayFlow(this.item, this.item.BillId, 5, this.item.Money, guahaoid)
							// 							const params = {
							// 								env: 'prod',
							// 								hospitalId: '37868',
							// 								redirectUrl: '/pagesB/pay/index',
							// 								sceneType: '2',
							// 								healthCardId: that.currentUserCard.ecard_no,
							// 								orderTotal: that.item.Money
							// 							}
							// 							uni.navigateTo({
							// 								url: `plugin://healthCardPlugins/complete?env=${params.env}&hospitalId=${params.hospitalId}&sceneType=${params.sceneType}&redirect_url=${encodeURIComponent(params.redirectUrl)}&orderTotal=${params.orderTotal}&healthCardId=${params.healthCardId}`
							// 							})
							// 							// uni.redirectTo({
							// 							// 	url: '/pages/global/successMessage?msg=缴费成功'
							// 							// })
							// 						} else {
							// 							// uni.showToast({
							// 							// 	title: '缴费失败',
							// 							// 	icon: "none"
							// 							// });
							// 							this.yangrMsgShow = true
							// 							this.yangrMsgMessage = '缴费失败'
							// 						}
							// 					})
							// 		})
							// 	// }
							// }).catch((err) => {
							// 	console.log('支付失败:' + JSON.stringify(err));
							// 	if (err.errMsg ==
							// 		'requestPayment:fail cancel') {
							// 		that.affirmModalVisible = false
							// 		uni.showToast({
							// 			icon: 'none',
							// 			title: '您已取消支付'
							// 		})
							// 	} else {
							// 		uni.showToast({
							// 			icon: 'none',
							// 			title: '支付异常'
							// 		})
							// 	}
							// })
						})
					})
			}
		}
	}
</script>

<style scoped lang="scss">
	.item-detail {
		border-radius: 6px;
		border: 1px solid #e3e3e3;
		padding: 10px;
		line-height: 30px;
		background-color: #f5f5f5;
		font-size: .9rem;
		color: #757575;
		margin-bottom: 5px;
	}

	.total-price {
		font-size: 1.1rem;
		color: #ff9800;
		line-height: 30px;
	}
</style>